package cn.itcast.user.dao;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

import javax.management.RuntimeErrorException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import cn.itcast.user.domain.User;

/*
 * User数据层（持久层）
 * 
 */
public class UserDao {
	private String path = "D:/user.xml";	
	
	public User findUserByName(String username) {
		/*
		 * 1,得到Document对象
		 */
		SAXReader reader = new SAXReader();
		try {
			Document doc = reader.read(path);
		
			/*
			 * 2,通过xpath来查询element
			 */
			Element element = (Element) doc.selectSingleNode("//user[@username='" + username +"']");
			
			/*
			 * 3,校验element是否为空
			 */
			if (element == null) return null;
			
			/*
			 * 4,把element数据封装进User对象中
			 * 
			 */
			User user = new User();
			String uname = element.attributeValue("username");
			String pwd = element.attributeValue("password");
			user.setPassword(pwd);
			user.setUsername(uname);

			return user;
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}

	public void add(User user) {
		/*
		 * 1,得到Document对象
		 */
		SAXReader reader = new SAXReader();
		try {
			Document doc = reader.read(path);

			//得到根元素
			Element root = doc.getRootElement();
			//通过根元素创建新元素
			Element userEle = root.addElement("user");
			//为userEle设置属性
			userEle.addAttribute("username", user.getUsername());
			userEle.addAttribute("password", user.getPassword());
			//保存doc文档
			//创建输出格式化器
			OutputFormat format = new OutputFormat("\t", true);
			format.setTrimText(true);
			//创建XML Writer
			XMLWriter writer;
			writer = new XMLWriter(
						new OutputStreamWriter(
								new FileOutputStream(path)), format);
			writer.write(doc);
			writer.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}
}
